package com.sz.mes.excel.listener;

import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.ContextHelper;
import com.diboot.core.util.V;
import com.sz.mes.excel.model.ProductTaskImportModel;
import com.sz.mes.excel.model.RequestPurchaseImportModel;
import com.diboot.file.excel.listener.FixedHeadExcelListener;
import com.sz.mes.entity.RequestPurchase;
import com.sz.mes.service.ProductTaskService;
import com.sz.mes.service.RequestPurchaseService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* 请购订单 导入Listener定义
* @author hem
* @version 1.0
* @date 2024-01-10
* Copyright © szhs
*/
public class RequestPurchaseImportListener extends FixedHeadExcelListener<RequestPurchaseImportModel> {
    private static final String RECEIPT_NUM = BeanUtils.convertToFieldName(RequestPurchaseImportModel::getReceiptNum);

    /**
    * 自定义校验规则
    * @param dataModelList    待保存的数据
    * @param requestParams  请求参数
    */
    @Override
    protected void additionalValidate(List<RequestPurchaseImportModel> dataModelList, Map<String, Object> requestParams) {
        // 附加校验
        // 对 单据编号、行号是否重复进行校验
        List<String> receiptNumAndRowList = new ArrayList<>();
        for (RequestPurchaseImportModel requestPurchaseImportModel : dataModelList) {
            if (receiptNumAndRowList.contains(requestPurchaseImportModel.getReceiptNum()
                    + "-" + requestPurchaseImportModel.getReceiptNumRow())) {
                requestPurchaseImportModel.addComment(RECEIPT_NUM, "单据编号或行号重复");
            }
            receiptNumAndRowList.add(requestPurchaseImportModel.getReceiptNum()
                    + "-" + requestPurchaseImportModel.getReceiptNumRow());

        }
        // 对单据编号及料品编号在系统中是否重复进行校验
        List<String> duplicateList = ContextHelper.getBean(RequestPurchaseService.class).filterDuplicate(receiptNumAndRowList);
        for (String duplicate : duplicateList) {
            dataModelList.get(receiptNumAndRowList.indexOf(duplicate)).addComment(RECEIPT_NUM, "该单据编号或行号在系统中已存在");
        }
    }

    /**
    * 保存数据
    * @param dataModelList 待保存的数据
    * @param requestParams 请求参数
    */
    @Override
    protected void saveData(List<RequestPurchaseImportModel> dataModelList, Map<String, Object> requestParams) {
        if (V.isEmpty(dataModelList)) {
            return;
        }
        List<RequestPurchase> entityList = BeanUtils.convertList(dataModelList, RequestPurchase.class);
        ContextHelper.getBean(RequestPurchaseService.class).createEntities(entityList);
    }
}
